
import { _decorator, Component, Node, Vec3, ICollisionEvent, ColliderComponent } from 'cc';
import { MonsterView } from './MonsterView';
const { ccclass, property } = _decorator;

/**
 * 子弹的控制程序和视图类的结合体
 */
@ccclass('BulletView')
export class BulletView extends Component {
    private _speed: number = 10             //速度
    private _flyDir: Vec3 = new Vec3();     //飞行方向.
    private _offset: Vec3 = new Vec3();


    start() {
        //注册碰撞检测
        let Collider = this.node.getComponent(ColliderComponent)!;
        Collider.on('onTriggerEnter', this._onTriggerEnter, this);
    }

    //初始化函数,用于设定子弹飞行的方向
    public init(targetPos: Vec3) {
        //向量减法函数
        Vec3.subtract(this._flyDir, targetPos, this.node.worldPosition)
        this._flyDir = this._flyDir.normalize();
    }

    update(dt: number) {
        //设置初始坐标
        this._offset.set(this.node.worldPosition)
        //计算变化量  向量乘以标量
        let delta = new Vec3();
        Vec3.multiplyScalar(delta, this._flyDir, dt * this._speed)
        //添加计算结果
        this._offset.add(delta)
        this.node.setWorldPosition(this._offset)
        if (this._offset.z < -20) {
            this._dispose();
        }
    }


    //碰撞回调
    private _onTriggerEnter(event: ICollisionEvent) {
        //得到敌人的碰撞器
        const otherCollider = event.otherCollider
        //得到敌人身上的视图组件
        const monsterView = otherCollider.getComponent(MonsterView)
        if (monsterView) {
            //调用敌人身上的受伤函数
            monsterView.onHurt()
        }
        this._dispose()
    }

    //子弹回收
    private _dispose() {
        this.node.destroy()
    }



}

